package com.xizi.producer;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @author xizizzz
 * @description: 回调方法发送消息
 * @date 2021-7-3上午 10:49
 */
public class CallBackProducer {
    public static void main(String[] args) throws Exception {
        //1. 创建Kafka生产者的配置信息
        Properties props = new Properties();
        //2. 指定连接的Kafka集群  broker-list
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "zookeeper1:9092");

        //8. key value序列化类
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //9. 创建生产者对象
        Producer<String, String> producer = new KafkaProducer<>(props);
        //10. 发送数据
        for (int i = 0; i < 10; i++) {
            //指定数据发送到0号分区
            producer.send(new ProducerRecord<>("aaa", 0, "xizi666", "xizizzz--" + i), new Callback() {
                //回调函数， 该方法会在 Producer 收到 ack 时调用，为异步调用
                @Override
                public void onCompletion(RecordMetadata metadata, Exception exception) {
                    if (exception == null) {
                        System.out.println(metadata.topic() + "--" + metadata.partition() + "--" + metadata.offset());
                    } else {
                        exception.printStackTrace();
                    }
                }
            });
        }
        //11. 关闭资源
        producer.close();
    }
}
